# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from typing import Any

import scrapy
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy import Request
from scrapy.http import Response
from scrapy.pipelines.files import FilesPipeline
from scrapy.pipelines.media import MediaPipeline


class KugouPipeline:
    def process_item(self, item, spider):
        return item


class AudioDownloadPipeline(FilesPipeline):
    def get_media_requests(
        self, item: Any, info: MediaPipeline.SpiderInfo
    ) -> list[Request]:
        if info.spider.name == 'music':
            try:
                yield scrapy.Request(
                    url=item['url'],
                    headers={'Referer': 'https://www.kugou.com/'},
                    meta={'item': item},
                )
            except Exception as e:
                name = item['name']
                with open(r'./download_error.txt', 'a',encoding='utf-8') as f:
                    f.write(f'{name}下载失败\n')

    def file_path(
        self,
        request: Request,
        response: Response | None = None,
        info: MediaPipeline.SpiderInfo | None = None,
        *,
        item: Any = None,
    ) -> str:
        return request.meta['item']['name']
